package com.lagou.rocket.demo.order.consumer;

import com.lagou.rocket.demo.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-11-07
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "check_pay_listener", topic = "check_pay")
public class CheckPayListener implements RocketMQListener<Long> {


    private final IOrderService orderService;

    private final RedisTemplate redisTemplate;

    // 库存预检查key的前缀
    private final static String PREFIX = "inventory_";


    public CheckPayListener(IOrderService orderService, RedisTemplate redisTemplate) {
        this.orderService = orderService;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public void onMessage(Long message) {
        // 这个消息的消费应该是幂等的
        log.info("消费检查订单状态消息, orderId: {}", message);
        String productCode = orderService.checkOrderStatusAndRestoreInventoryIfNeeded(message);

        if (StringUtils.isNotBlank(productCode)){
            // 增加redis的库存
            String inventoryKey = PREFIX + productCode;
            Long increment = redisTemplate.opsForValue().increment(inventoryKey);
            log.info("增加之后的库存为： {}", increment);
        }

    }
}
